package com.hmall.item.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.mapper.ItemMapper;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ItemService extends ServiceImpl<ItemMapper, Item> implements IItemService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public PageDTO<Item> listByPage(int page, int size) {
        // 构建分页条件
        IPage<Item> iPage = new Page<>(page, size);
        // 构建查询条件
        LambdaQueryWrapper<Item> query = new LambdaQueryWrapper<>();
        // 按照最后修改时间倒序排列
        query.orderByDesc(Item::getUpdateTime);
        IPage<Item> itemIPage = this.page(iPage, query);
        // 构建响应对象
        PageDTO<Item> result = new PageDTO<>(itemIPage.getTotal(), itemIPage.getRecords());
        return result;
    }

    @Override
    public void add(Item item) {
        // 添加创建时间和更新时间
        item.setCreateTime(new Date());
        item.setUpdateTime(new Date());
        // 保存
        this.save(item);

        // 发送消息到MQ
        rabbitTemplate.convertAndSend("item.direct", "item.update", JSON.toJSONString(item));
    }

    @Override
    public void updateItem(Item item) {
        // 修改更新时间
        item.setUpdateTime(new Date());
        // 执行更新
        this.updateById(item);

        // 发送消息到MQ
        rabbitTemplate.convertAndSend("item.direct", "item.update", JSON.toJSONString(item));
    }

    @Override
    public void deleteItem(Long id) {
        // 删除
        this.removeById(id);

        // 发送消息到MQ
        rabbitTemplate.convertAndSend("item.direct", "item.delete", id.toString());
    }

    @Override
    public void reduceStock(Long id, Integer num) {
        LambdaUpdateWrapper<Item> update = new LambdaUpdateWrapper<>();
        update.eq(Item::getId, id);
        update.setSql("stock = stock - " + num);
        this.update(update);

        // 模拟异常
        // int i = 1 / 0;
        // 发送消息到MQ
    }
}
